package mcp

import (
	"context"
	"fmt"

	"github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
	"github.com/sirupsen/logrus"

	"github.com/dreamSailing/http-proxy/internal/proxy"
)

// 硬编码的MCP配置常量
const (
	MCPName        = "http-proxy"
	MCPVersion     = "1.0.0"
	MCPDescription = "基于Go语言开发的MCP HTTP代理服务，专为AI工具提供HTTP请求能力"
)

// Server MCP服务器
type Server struct {
	logger      *logrus.Logger
	proxyEngine *proxy.Engine
	mcpServer   *server.MCPServer
	ctx         context.Context
	cancel      context.CancelFunc
}

// NewServer 创建新的MCP服务器
func NewServer(logger *logrus.Logger, proxyEngine *proxy.Engine) (*Server, error) {
	ctx, cancel := context.WithCancel(context.Background())

	s := &Server{
		logger:      logger,
		proxyEngine: proxyEngine,
		ctx:         ctx,
		cancel:      cancel,
	}

	mcpServer := server.NewMCPServer(
		MCPName,
		MCPVersion,
	)

	httpProxyTool := mcp.NewTool(
		"http-proxy",
		mcp.WithDescription("An HTTP proxy tool that allows making HTTP requests on behalf of the client."),
	)

	mcpServer.AddTool(httpProxyTool, s.httpProxyHandler)

	s.mcpServer = mcpServer
	return s, nil
}

// httpProxyHandler HTTP代理工具的处理器
func (s *Server) httpProxyHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	s.logger.Infof("Handling http-proxy request with params: %v", request.GetArguments())

	var httpReq proxy.HTTPRequest
	if err := request.BindArguments(&httpReq); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("failed to bind arguments: %v", err)), nil
	}

	resp, err := s.proxyEngine.PerformRequest(ctx, &httpReq)
	if err != nil {
		s.logger.Errorf("Failed to perform HTTP request: %v", err)
		return mcp.NewToolResultError(fmt.Sprintf("failed to perform request: %v", err)), nil
	}

	s.logger.Infof("Successfully performed HTTP request to %s with status %d", httpReq.URL, resp.StatusCode)

	// 返回完整的响应数据，包括状态码、头部、响应体等
	resultText := fmt.Sprintf("HTTP %s request to %s completed\nStatus: %d\nResponse Time: %dms",
		httpReq.Method, httpReq.URL, resp.StatusCode, resp.ResponseTimeMs)

	if resp.Error != "" {
		resultText += fmt.Sprintf("\nError: %s", resp.Error)
	}

	if resp.Body != "" {
		resultText += fmt.Sprintf("\nResponse Body: %s", resp.Body)
	}

	return mcp.NewToolResultStructured(resp, resultText), nil
}

// Start 启动MCP服务器
func (s *Server) Start(ctx context.Context) error {
	s.logger.Infof("Starting MCP server '%s' version '%s'", MCPName, MCPVersion)
	return server.ServeStdio(s.mcpServer)
}

// Shutdown 停止MCP服务器
func (s *Server) Shutdown(ctx context.Context) error {
	s.logger.Info("Stopping MCP server...")
	s.cancel()
	return nil
}
